#include <signal.h>
#include <time.h>
#include <cstdlib>
#include <cstring>
#include "BaseServer.h"

static void int_handler(int signum)
{
	if ( BaseServer::instance != NULL )
		BaseServer::instance->Terminate();
}

static void hup_handler(int signum)
{
	if ( BaseServer::instance != NULL )
		BaseServer::instance->reloadConfig();
}

BaseServer * BaseServer::instance = NULL;

BaseServer::BaseServer(const std::string & name)
{
	strncpy(Entry::name, name.c_str(), Entry::MAXNAMESIZE );
	terminate = false;
	instance = this;
}

bool BaseServer::init()
{
	struct sigaction sig;
	sig.sa_handler = int_handler;
	sigaction(SIGINT, &sig, NULL);
	sigaction(SIGQUIT, &sig, NULL);
	sigaction(SIGABRT, &sig, NULL);
	sigaction(SIGTERM, &sig, NULL);
	sig.sa_handler = hup_handler;
	sigaction(SIGHUP, &sig, NULL);

	sig.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sig, NULL);

	srand(time(NULL));

	return true;
}

void BaseServer::mainLoop()
{
	if ( init() )
	{
		while( !isTerminate() )
		{
			listenForeign();
		}
	}
	recycle();	/* join threads, stop tcptaskpool */
}

